//
//  WBLoginViewController.swift
//  Swift_sina
//
//  Created by TFB_WGP on 2017/9/4.
//  Copyright © 2017年 TFB_WGP. All rights reserved.
//

import UIKit
import WebKit
import SVProgressHUD

class WBLoginViewController: UIViewController {
    
    fileprivate lazy var webView: WKWebView = {
        let webView = WKWebView()
        webView.navigationDelegate = self
        webView.scrollView.isScrollEnabled = false
        return webView
    }()
    var progressView: UIProgressView?
    
    override func loadView() {
        view = webView
        view.backgroundColor = UIColor.white
        
        title = "新浪微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", fontSize: btnFont, normalColor: UIColor.darkGray, target: self, action: #selector(autoFill))
    }
    
    @objc func autoFill(){
        //修改本地浏览器中缓存的数据
        let js = "document.getElementById('userId').value = '18225529869';" + "document.getElementById('passwd').value = 'abc18225529869';"
        webView.evaluateJavaScript(js, completionHandler: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //初始化
        progressView = UIProgressView(frame: CGRect(x: 0, y: 65, width: SCREEN_WIDTH, height: 2))
        progressView?.backgroundColor = UIColor.blue
        webView.addSubview(progressView!)
        
        //KVO
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirect_uri)"
        guard let url = URL.init(string: urlString) else {
            return
        }
        webView.load(URLRequest(url: url))
    }
    
    @objc func close(){
        dismiss(animated: true, completion: nil)
    }
    
    //KVO回调
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            progressView?.progress = Float(webView.estimatedProgress)
//            WPPrint(items: webView.estimatedProgress)
            
            if progressView?.progress == 1 {
                
                weak var weakSelf = self
                UIView.animate(withDuration: 0.25, animations: { 
                    weakSelf?.progressView?.transform = CGAffineTransform(scaleX: 1.0, y: 1.4)
                }, completion: { (finished) in
                    self.progressView?.isHidden = true
                })
            }
        }else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }
    
    deinit{
        webView.removeObserver(self, forKeyPath: "estimatedProgress")
    }
}

extension WBLoginViewController:WKNavigationDelegate {
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        //取消授权跳转https://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        //授权成功后的跳转https://www.baidu.com/?code=782397468b43c979c5214136309de025
        
        guard let url = navigationAction.request.url else {
            decisionHandler(.cancel)
            return
        }
//        WPPrint(items: "加载url: \(url.absoluteString)")
        
        if url.absoluteString.hasPrefix("https://www.baidu.com/") {
            
            if (url.query?.hasPrefix("code="))! {
                WPPrint(items: "成功授权")
                
                let code = url.query?.substring(from: "code=".endIndex) ??  ""
                //使用授权码获取accessToken
                NetworkRequest.sharedInstance.loadAccessToken(code: code, completion: { (isSuccess) in
                    
                    if isSuccess {
                        SVProgressHUD.showSuccess(withStatus: "登陆成功")
                        //跳转界面,发送登录成功消息
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginSuccessNotifiction), object: nil)
                        //关闭窗口
                        self.close()
                        
                    }else{
                        SVProgressHUD.showError(withStatus: "登录失败")
                    }
                })
            }
            else {
                WPPrint(items: "取消授权")
                close()
            }
            decisionHandler(.cancel)
        }else {
            
            decisionHandler(.allow)
        }
    }
    
    //开始加载
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        
        progressView?.isHidden = false
        view.bringSubview(toFront: progressView!)
    }
    //加载完成
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        progressView?.isHidden = true
    }
    //加载失败
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        progressView?.isHidden = true
    }
}
